import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
@WebServlet(CookieTest)
public class CookieTest extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        设置响应的消息体和数据格式以及编码
        resp.setContentType(texthtml;charset=utf-8);

        获取所有Cookie
        Cookie[] cookies = req.getCookies();
        boolean flag=false;没有Cookie为lastTime
        遍历Cookie
        if (cookies != nullcookies.length0) {
            for (Cookie cookiecookies) {
                获取Cookie名称
                String name = cookie.getName();
                判断是否是：lastTime
                if (lastTime.equals(name)) {
                    有该Cookie，不是第一次访问
                    flag=true;有lastTime的Cookie


                    设置Cookie的value
                    获取当前时间的字符串，重新设置Cookie的值，重新发送Cookie
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat(yyyy年MM月dd日HHmmss);
                    String srt_date = sdf.format(date);
                    cookie.setValue(srt_date);
                    设置Cookie的存活时间
                    cookie.setMaxAge(60602430);
                    resp.addCookie(cookie);

                    响应数据
                    获取Cookie的value时间
                    String value = cookie.getValue();
                    resp.getWriter().write(h1欢迎回来，您上次访问的时间为+value+h1);
                    break;
                }
            }
        }
        if (cookies==nullcookies.length==0flag==false) {
            没有,第一次访问
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat(yyyy年MM月dd日HHmmss);
            String srt_date = sdf.format(date);
            Cookie cookie=new Cookie(lastTime,srt_date);
            设置Cookie的存活时间
            cookie.setMaxAge(60602430);
            resp.addCookie(cookie);

            resp.getWriter().write(h1您好,欢迎您首次访问h1);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
